package me.luger.core.auth.cookie.util;

import com.alibaba.fastjson.JSONObject;
import me.luger.core.commom.util.*;
import me.luger.core.mvc.WebService;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by luger on 2017/5/10.
 */
public class CookieAuthUtil {

    public static String DES_PASSWORD = "lugerlin";

    public static boolean setAuthCookie(HttpServletRequest request, HttpServletResponse response, String uid){
        String ip = HttpUtil.getRemoteAddr(request);
        Map<String,String> cookieMap = new HashMap<String,String>();
        cookieMap.put("ip",ip);
        cookieMap.put("uid",uid);
        String key = JsonUtil.toString(cookieMap);
        String projectName = WebService.getProjectName();
        try {
            key = EncryptUtils.encryptToDES(DES_PASSWORD,key);
        } catch (Exception e) {
            LogUtil.errorLog(e,"");
        }
        CookieUtil.setCookie(response,60*60*24*7,"/",projectName + "_key",key);
        return true;
    }

    public static boolean clearAuthCookie(HttpServletResponse response){
        String projectName = WebService.getProjectName();
        CookieUtil.clearRootCookie(response,projectName + "_key");
        return true;
    }

    public static Map<String,String> getAuthCookie(HttpServletRequest request){
        if(null == request){
            return null;
        }
        String projectName = WebService.getProjectName();
        String cookieValue = CookieUtil.getCookie(request,projectName + "_key");
        Map<String,String> cookieMap = null;
        try{
            cookieValue = EncryptUtils.decryptByDES(DES_PASSWORD,cookieValue);
            cookieMap = JsonUtil.parse(cookieValue,Map.class);
        }catch (Exception e){
            LogUtil.errorLog(e,"getAuthCookie error");
        }
        return cookieMap;
    }
}
